package com.shareyi.wox.util;

import java.io.File;
import java.util.HashSet;
import java.util.List;

import org.apache.commons.digester3.Digester;
import org.apache.commons.digester3.binder.DigesterLoader;
import com.shareyi.wox.config.WoxConfig;
import com.shareyi.wox.config.WoxConfigException;
import com.shareyi.wox.config.WoxParseRulesModel;
import com.shareyi.fileutil.FileUtil;

public class WoxConfigParseUtils {

	 HashSet<String> parsedPath=new HashSet<String>();
	 DigesterLoader loader = DigesterLoader.newLoader(new WoxParseRulesModel());
	 WoxConfig woxConfig=null;
	 
	 
	 public  WoxConfig parseWoxConfig(File configFile) throws WoxConfigException{
		 this.woxConfig=new WoxConfig();
		 parseWoxConfigFile(configFile);
		 return this.woxConfig;
		}
	 
	 
	public  WoxConfig parseWoxConfigFile(File configFile) throws WoxConfigException{
		//防止配置文件数据重复
		 Digester digester=loader.newDigester();
		  WoxConfig woxConfig2;
		try {
			woxConfig2 = digester.parse(configFile);
		} catch (Exception e) {
			throw new WoxConfigException("parse wox configuartion file failed", e);
		}
		  parsedPath.add(configFile.getAbsolutePath());
		  this.parseIncludeFiles(woxConfig);
		  woxConfig.merge(woxConfig2);
		 return woxConfig;
	}



	public void parseIncludeFiles(WoxConfig woxConfig) throws WoxConfigException {
		List<String> includeFiles=woxConfig.getIncludeFiles();
		if(!includeFiles.isEmpty()){  //不为空，继续解析子文件
			for (String str : includeFiles) {
				String filePath=FileUtil.contactPath(FileUtil.getRunPath(),str);
				File f=new File(filePath);
				if(f.exists()&&f.isFile()){
					parseWoxConfigFile(f);
				}else{
					throw new WoxConfigException("");
				}
			}
		  }
	}
}
